"use strict"

const mysql = require('mysql2/promise')
const config = require('../config')
const _ = require('lodash/fp')

const store = data => {
    let connect = null
    const gen_query = sql => () => connect.query(sql)

    const ids = `("${_.pluck('id', data).join('","')}")`

    const needle_sql = `SELECT id,name,url,room_name FROM ${config.table} WHERE id IN ${ids} AND ${config.off_line}`

    const delete_sql = `DELETE FROM ${config.table} WHERE id IN ${ids}`

    const update_sql = `UPDATE ${config.table} SET ${config.off_line}`

    const insert_sql = `INSERT INTO ${config.table} (${config.cols.join(',')},status) VALUES ${
        data.map(row => `(${config.cols.map(col => `'${row[col]}'`).join(',')},1)`).join(',')
        }`

    return mysql
        .createConnection(config.DB)
        .then(c => connect = c)
        //.then(gen_query(needle_sql))
        .then(rows => {
            //把需要推送的查询结果返回给主循环，其余查询异步进行
            gen_query('begin')()
                .then(gen_query(delete_sql))
                .then(gen_query(update_sql))
                .then(gen_query(insert_sql))
                .then(gen_query('commit'))
                .then(_ => connect.end())
                .catch(sql_error => {
                    connect.end()
                    console.error(sql_error)
                })
            //return get_needs(rows[0])
        })
}

const get_needs = anchors => {
    const pool = mysql.createPool(config.DB)
    let pool_ends = []

    const query = sql => {
        const query = pool.query(sql)
        pool_ends.push(query)
        return query
    }

    const throttle = (interval, anchors) => {
        const pushed = `SELECT id,pushed_at FROM qyg_anchor_ex WHERE id IN ('${_.map('id', anchors).join("','")}')`
        const now = Math.floor(new Date().getTime() / 1000)
        return query(pushed)
            .then(pushed => {
                const ids = _.map('id', pushed[0])
                let needs = []
                for (let anchor of anchors) {
                    const push = _.find({ id: anchor.id }, pushed[0])

                    if (push) {
                        if (parseInt(push.pushed_at) < now - interval) {
                            query(`UPDATE qyg_anchor_ex SET pushed_at = ${now} WHERE id = '${anchor.id}'`)
                            needs.push(anchor)
                        }
                    } else {
                        //push insert
                        query(`INSERT INTO qyg_anchor_ex(id, pushed_at) VALUES('${anchor.id}', ${now})`).catch(console.error)
                        needs.push(anchor)
                    }
                }
                return needs
            })
            .catch(console.error)
    }

    const get_need_users = anchor => query(`
            SELECT wx_open_id2 FROM qyg_users as users, qyg_user_anchor as u_a 
            WHERE u_a.anchor_id = '${anchor.id}'
            AND u_a.user_id = users.id 
            AND users.wx_open_id2 IS NOT NULL
            AND u_a.subscribe = 1
        `)
        .then(rows => _.map('wx_open_id2', rows[0]))
        .then(users => ({ anchor: anchor, users: users }))

    return throttle(7200, anchors)
        .then(_.map(get_need_users))
        .then(_ => Promise.all(_))
        .then(_.filter(_ => _.users.length))
        .then(_ => {
            Promise.all(pool_ends).then(_ => pool.end())
            return _
        })
        .catch(_ => pool.end())
}

module.exports = store